package entity

import "github.com/jinzhu/gorm"

type Article struct {
	*gorm.Model
	Title       string
	Content     string
	CategoryId  uint
	PageView    uint
	CoverUrl    string
	Quote       string
	Recommended bool
	IsPublic    bool
	Liked       uint
}

func (a Article) Create(db *gorm.DB) (*Article, error) {
	err := db.Create(&a).Error
	if err != nil {
		return nil, err
	}
	return &a, nil
}

func (a Article) List(db *gorm.DB, offset int, pageSize int) ([]Article, error) {
	var list []Article
	err := db.Limit(pageSize).Offset(offset).Order("created_at desc").Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (a Article) FirstPageArticleList(db *gorm.DB, offset int, pageSize int) ([]Article, error) {
	var list []Article
	err := db.Limit(pageSize).Offset(offset).Order("created_at desc").Where("recommended=?", 1).Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (a Article) Get(db *gorm.DB) (*Article, error) {
	err := db.Find(&a).Where("id = ?", a.ID).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &a, nil
}

func (a Article) Count(db *gorm.DB) (uint, error) {
	var cnt uint
	err := db.Model(&a).Count(&cnt).Error
	return cnt, err
}

func (a Article) GetArticlesByCategoryID(db *gorm.DB, offset int, pageSize int) ([]Article, error) {
	var list []Article
	err := db.Where("category_id=?", a.CategoryId).Limit(pageSize).Offset(offset).Order("created_at desc").Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (a Article) CountByClassID(db *gorm.DB) (uint, error) {
	var cnt uint
	err := db.Model(&a).Where("category_id=?", a.CategoryId).Count(&cnt).Error
	return cnt, err
}

func (a Article) GetBySearchText(db *gorm.DB, text string) ([]Article, error) {
	var articles []Article
	err := db.Where("title like ?", "%"+text+"%").Find(&articles).Error
	return articles, err
}

func (a Article) DeleteById(db *gorm.DB, id uint) error {
	return db.Delete(&Article{}, id).Error
}

func (a Article) UpdateById(db *gorm.DB) error {
	return db.Save(&a).Error
}
